from pycparser import c_ast, c_generator

def create_function_declaration(name, return_type, params):
    # 返回类型构造（无需名称）
    return_type_decl = c_ast.TypeDecl(
        declname='',  # 此处必须为空
        align=None,
        type=c_ast.IdentifierType([return_type]),
        quals=[]
    )

    # 参数列表构造
    param_list = []
    for param_type, param_name in params:
        param_decl = c_ast.Decl(
            name=param_name,
            quals=[],
            storage=[],
            funcspec=[],
            align=None,
            type=c_ast.TypeDecl(
                align=None,
                declname=param_name,
                type=c_ast.IdentifierType([param_type]),
                quals=[]
            ),
            bitsize=None,
            init=None
        )
        param_list.append(param_decl)

    # 关键修正：构建函数声明节点
    func_decl = c_ast.Decl(
        name=name,  # 函数名在此处设置
        quals=[],
        storage=['extern'],  # 明确声明属性
        funcspec=[],
        align=None,
        bitsize=None,
        type=c_ast.FuncDecl(
            args=c_ast.ParamList(param_list),
            type=return_type_decl
        ),
        init=None  # 确保无函数体
    )

    return func_decl

# 验证输出
if __name__ == "__main__":
    func_node = create_function_declaration(
        name='add',
        return_type='int',
        params=[('int', 'a'), ('int', 'b')]
    )
    func_node.show()
    generator = c_generator.CGenerator()
    print(generator.visit(func_node))  # 输出：extern int add(int a, int b);